package com.shioirikukuri.controller;

import com.shioirikukuri.entity.Category;
import com.shioirikukuri.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {

	@Autowired
	private ICategoryService categoryService;

	/**
	 * 获取所有分类
	 * @return
	 */
	@GetMapping
	public ResponseEntity<List<Category>> getAllCategories() {
		List<Category> categories = categoryService.getAllCategories();
		return ResponseEntity.ok(categories);
	}

	/**
	 * 获取分类详情
	 * @param id
	 * @return
	 */
	@GetMapping("/{id}")
	public ResponseEntity<?> getCategoryById(@PathVariable Long id) {
		Optional<Category> category = categoryService.getCategoryById(id);
		if (category.isPresent()) {
			return ResponseEntity.ok(category.get());
		} else {
			return ResponseEntity.notFound().build();
		}
	}

	/**
	 * 添加分类
	 * @param category
	 * @return
	 */
	@PostMapping
	public ResponseEntity<Category> addCategory(@RequestBody Category category) {
		Category createdCategory = categoryService.addCategory(category);
		return ResponseEntity.status(201).body(createdCategory);
	}

	/**
	 * 更新分类
	 * @param id
	 * @param category
	 * @return
	 */
	@PutMapping("/{id}")
	public ResponseEntity<?> updateCategory(@PathVariable Long id, @RequestBody Category category) {
		try {
			Category updatedCategory = categoryService.updateCategory(id, category);
			return ResponseEntity.ok(updatedCategory);
		} catch (Exception e) {
			return ResponseEntity.notFound().build();
		}
	}

	/**
	 * 删除分类
	 * @param id
	 * @return
	 */
	@DeleteMapping("/{id}")
	public ResponseEntity<Void> deleteCategory(@PathVariable Long id) {
		categoryService.deleteCategory(id);
		return ResponseEntity.noContent().build();
	}
}
